package com.oschina.util;

import com.oschina.common.Constants;
import org.springframework.util.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Neil
 */
public class Utils {

    public static Map<String, String> changeMapBtye2String(Map<byte[], byte[]> map) {
        Map<String, String> resMap = new HashMap<String, String>();
        for (byte[] cpB : map.keySet()) {
            try {
                resMap.put(new String(cpB, "utf-8"), new String(map.get(cpB), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return resMap;
    }


    /**
     * string --> map
     *
     * @param input
     * @return
     */
    public static Map<String, String> stringToMap(String input) {
        if (StringUtils.isEmpty(input)) return null;
        Map<String, String> map = new HashMap<String, String>();
        if (input != null && input.length() > 0) {
            String[] params = null;
            if (input.indexOf("&") != -1) {
                params = input.split("&");
            } else {
                params = input.split(",");
            }
            for (String param : params) {
                String[] arr = param.split("=");
                if (arr.length > 1) {
                    map.put(arr[0], arr[1]);
                }
            }
        }
        return map;
    }

    /**
     * 转换set中的byte为string
     *
     * @param s
     * @return
     */
    public static Set<String> byte2string(Set<byte[]> s) {
        Set<String> res = new HashSet<String>();
        if (s == null || s.isEmpty()) {
            return res;
        }
        for (byte[] strByte : s) {
            try {
                res.add(new String(strByte, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static String getExceptionMessage(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }


    public static int getPage(int recCount) {
        if (recCount % Constants.PAGE_COUNT == 0)
            return recCount / Constants.PAGE_COUNT;
        else
            return recCount / Constants.PAGE_COUNT + 1;
    }

    public static int getPageIndex(int pageIndex) {
        return pageIndex * Constants.PAGE_COUNT;
    }

}
